<template>
  <view class="notesPage_box">
    <!-- 无数据-缺省頁 -->
    <DefaultPage
      tips="暂时没找到相关带货笔记"
      :custoBtn="true"
      type="2"
      :minusHeight="0"
      v-if="!graphicList.length && !getParams.loading"
    >
    </DefaultPage>
    <!-- 视频列表 -->
    <ScrollList
      :minusHeight="0"
      ref="videoScrollView"
      @scroll="scrollFn"
      @interrupt="interruptFn"
      v-else
      @scrolltolower="scrolltolower"
    >
    <template slot="content" class="u-m-t-24">
      <view class="notes_msg_list" v-for="(graphic,index) in graphicList" :key="index">
        <view class="notes_data_box">
          <!-- 用户信息 -->
          <view class="user_box items-center u-m-b-24">
            <image class="user_head_img" mode="aspectFill" :src="graphic.communityLogo || 'https://image.qqpyyds.com/mpAppImg/icon/avatar2_icon.png'" alt="">
            <text class="fz-14">{{graphic.communityName}}</text>
            <text class="identifying_box" v-if="graphic.isSuperior">供货</text>
          </view>
          <!-- 图片区域 -->
          <ImageLayout v-if="graphic.mediaType==1" :images="graphic.materialMediaRespVOList"/>
          <!-- 视频区域 -->
          <video
            v-if="graphic.mediaType==2"
            :id="`myVideo${index}`"
            :ref="`myVideo${index}`"
            :class="graphic.materialMediaRespVOList[0].high > graphic.materialMediaRespVOList[0].wide?'video_file_box_two':'video_file_box'"
            :src="graphic.materialMediaRespVOList[0].url"
            :poster="graphic.materialMediaRespVOList[0].url + '?x-oss-process=video/snapshot,t_100,f_jpg'"
            :object-fit="graphic.materialMediaRespVOList[0].high > graphic.materialMediaRespVOList[0].wide ? 'cover' : 'contain'"
            loop
            :controls="false"
            :enable-progress-gesture="false"
            :show-center-play-btn="false"
            @click.stop="clickPlayFn(index)"
          >
            <image class="play_btn_box" v-if="!graphic.viodeIsPlay" @click.stop="clickPlayFn(index)" src="https://image.qqpyyds.com/mpAppImg/icon/play1_icon.png" alt="" />
          </video>
          <!-- 标题 -->
          <view class="title_box" :class="{'title_box_two':graphic.showTitle}" :id="`myTitle${index}`">{{graphic.title}}</view>
          <view class="viewAll_btn viceColor u-m-t-20" v-if="graphic.showTitle" @click.stop="viewAllTitleFn(graphic,index)">查看全部</view>
          <!-- 数据展示 -->
          <!-- <view class="data_msg_list u-m-t-20">-->
          <!--   <view class="data_msg_box">-->
          <!--     <text class="">{{graphic.conversionRate || 0}}%</text>-->
          <!--     <p class="fz-10 viceColor u-m-t-8">转化率</p>-->
          <!--   </view>-->
          <!--   <view class="data_msg_box">-->
          <!--     <text>{{graphic.orderCount || 0}}</text>-->
          <!--     <p class="fz-10 viceColor u-m-t-8">成交数</p>-->
          <!--   </view>-->
          <!--   <view class="data_msg_box">-->
          <!--     <text>{{graphic.useCount || 0}}</text>-->
          <!--     <p class="fz-10 viceColor u-m-t-8">使用次数</p>-->
          <!--   </view>-->
          <!-- </view>-->
          <!-- 操作按钮 -->
          <view class="operation_btn_list u-m-t-20">
            <text class="red_txt">
              {{graphic.isNeedPay==1?`佣金的${graphic.needPayRatio}%`:'免费使用'}}
            </text>
            <button class="red_btn multiplex_btn" @click.stop="_copyMaterial(graphic)" hover-class="hover">
              <!-- {{graphic.isNeedPay==1?`${graphic.needPayRatio}%佣金复用`:'免费复用'}}-->
              立即复用
            </button>
          </view>
        </view>
      </view>
      <!-- <view class="notGoodsSquare" v-if="getParams.finish">没有更多了~</view>-->
    </template>
    </ScrollList>

    <!-- 复用笔记 -->
    <Modal 
    :show="clickMaterial.modelShow"
    title="复用带货笔记"
    :content="clickMaterial.content" 
    configText="立即复用"
    @close="clickMaterial.modelShow = false"
    @config="_configCopyMaterial" />
  </view>
</template>

<script>
import DefaultPage from "@/components/defaultPage/index.vue"
import ImageLayout from '@/components/imageLayout/index.vue'
import ScrollList from '@/components/scrollList/index.vue'
import release from "@/api/release.js"
import Modal from '@/components/modal/index.vue'
export default {
  components: { DefaultPage,ScrollList,Modal,ImageLayout },
  props: {
    sortType: {
      type: String | Number,
      default: '1'
    },
    spuId: {
      type: String | Number,
      default: ''
    },
    shopWindowId: {
      type: String | Number,
      default: ''
    }
  },
  watch: {
    sortType(nVal){
      let string0 = 'myVideo' + this.nowLivePlay
      let videoContext0 = uni.createVideoContext(string0,this)
      videoContext0.pause()  // 暂停当前
      this.getParams = {
        ...this.getParams,
        currentPage: 1,
        finish: false, // 是否还有更多
        sortType: nVal
      }
      this.topArr = []
      this.nowLivePlay = 0
      this.getGraphicListFn()
    }
  },
  data () {
    return {
      getParams: {
        currentPage: 1,
        pageSize: 10,
        finish: false, // 是否还有更多
        loading: true,
        sortType: 1,
        spuId: '',
        shopWindowId: '',
      },
      graphicList: [],
      timer: 0,
      topArr: [],
      nowLivePlay: 0,
      timeout: null,
      clickMaterial: {
        modelShow: false,
        materialId: "",
        content: ""
      },
      currerPlayViode: {
        ref: "",
        index: 0
      }, // 当前播放的video实例
    }
  },
  created() {
    this.getGraphicListFn()
  },
  methods: {
    // 点击笔记复用
    _copyMaterial(item){
      this.clickMaterial.materialId = item.materialId
      if(item.isNeedPay){ // 需要支付佣金
        this.clickMaterial.modelShow = true
        if(item.isGoodsIssuer && item.isGoodsIssuer === 1){ // 供货
          this.clickMaterial.content = "复用当前笔记发布后，卖货出单后，你需要将帮卖佣金的10%支付给笔记创作者。"
        }else{
          this.clickMaterial.content = "复用当前笔记发布后，卖货出单后，你需要将你获得佣金的10%支付给笔记创作者。"
        }
      }else{
        this._configCopyMaterial()
      }
    },
    // 确定复用
    _configCopyMaterial () {
      this.clickMaterial.modelShow = false
      this.navigateTo({url: `/pagesA/release/issueEdit?materialId=${this.clickMaterial.materialId}&shopWindowId=${this.shopWindowId}`})
    },

    // 加载笔记列表
    async getGraphicListFn () {
      this.getParams.loading = true
      this.getParams.spuId = this.spuId
      this.getParams.shopWindowId = this.shopWindowId
      const { data } = await release.getPageBySpuId(this.getParams)
      if (data.records) {
        data.records.forEach((item, i) => { // 处理image为字符串的问题
          data.records[i] = {
            ...data.records[i],
            showTitle: item.title.length>47?true:false, // 添加一个字段来判断显示隐藏查看全部
            viodeIsPlay: false //  添加一个字段来判断视频是否播放
          }
        })
        if (this.getParams.currentPage === 1) {this.graphicList = []} // 第一页初始化数据
        this.graphicList = [...this.graphicList,...data.records]

        // 如果第一个是视频，则自动播放
        // if (this.graphicList[0].mediaType == 2){
        //   let videoContext1 = uni.createVideoContext('myVideo0',this)
        //   this.graphicList[0].viodeIsPlay = true
        //   videoContext1.play()
        // }

        this.$nextTick(()=>{
          setTimeout(()=>{this.getIdFn()},500)
        })

        this.getParams.finish = this.getParams.currentPage * this.getParams.pageSize !== this.graphicList.length
      }
      this.getParams.loading = false
    },
    getIdFn() {
      const that = this
      for (let i =0; i < that.graphicList.length; i++) {
        that.topArr[i] = 0
        const query = this.createSelectorQuery()
        query.select('#myTitle' + i).boundingClientRect() //获取节点位置信息的查询请求
        query.selectViewport().scrollOffset(); // 获取页面滑动位置的查询请求
        query.exec((res) => {
          that.topArr[i] = res[0].top; //节点的上边界坐标
        })
      }
    },

    // 点击播放或者暂停
    clickPlayFn (index) {
      const that = this
      let presentVideo = uni.createVideoContext(`myVideo${index}`,that)
      if(that.graphicList[index].viodeIsPlay){ // 正在播放暂停
        that.graphicList[index].viodeIsPlay = false
        presentVideo.pause(); //暂停播放
      }else{// 暂停则继续播放
        if(that.currerPlayViode.ref){ // 存在上一个视频在播放
          that.graphicList[that.currerPlayViode.index].viodeIsPlay = false
          that.currerPlayViode.ref.pause(); //暂停播放
        }
        
        that.graphicList[index].viodeIsPlay = true
        presentVideo.play()

        that.currerPlayViode.ref = presentVideo
        that.currerPlayViode.index = index
      }

      // let that = this
      // let string0 = 'myVideo' + that.nowLivePlay
      // let videoContext0 = uni.createVideoContext(string0,that)
      // videoContext0.stop()  // 暂停当前
      // let string1 = 'myVideo' + index
      // let videoContext1 = uni.createVideoContext(string1,that)
      // videoContext1.play() // 播放下一个
      // that.nowLivePlay = index
    },
    
    scrollFn (res) { // 滚动计算
      // let that = this
		  // let top = Number(res.detail.scrollTop) + 190
      // that.topArr = that.topArr.sort((x, y) => {
      //   return x - y
      // })
      // if (that.timer) clearTimeout(that.timer)
      // that.timer = setTimeout(() => {
      //   for (let j = 0; j < that.topArr.length; j++) {
      //     if (that.topArr[j] > top) {
      //       let string0 = 'myVideo' + that.nowLivePlay
      //       let videoContext0 = uni.createVideoContext(string0,that)
      //       that.graphicList[that.nowLivePlay].viodeIsPlay = false
      //       videoContext0.stop()  // 暂停当前
      //       let string1 = 'myVideo' + j
      //       let videoContext1 = uni.createVideoContext(string1,that)
      //       if (this.graphicList[j].mediaType == 2){
      //         this.graphicList[j].viodeIsPlay = true
      //         videoContext1.play() // mediaType等于2表示是视频才播放下一个
      //       } 
      //       that.nowLivePlay = j
      //       return
      //     }
      //   }
      // }, 50)
    },
    // 加载更多
    async scrolltolower() {
      if (this.getParams.finish) {
        this.$refs.videoScrollView.loadFinish(3); // 加载完成，是否还有更多
        return
      }
      this.getParams.currentPage += 1
      await this.getGraphicListFn()
      this.$refs.videoScrollView.loadFinish(this.getParams.finish ? 3 : 0); // 加载完成，是否还有更多
    },
    // 下拉刷新方法，刷新完毕调用组件方法改变状态
    interruptFn() {
      if (this.timeout) clearTimeout(this.timeout)
      let string0 = 'myVideo' + this.nowLivePlay // 需要暂停视频
      let videoContext0 = uni.createVideoContext(string0,this)
      this.graphicList[this.nowLivePlay].viodeIsPlay = false
      videoContext0.pause(); //暂停播放
      this.timeout = setTimeout(() => {
        this.getParams.finish = false
        this.getParams.currentPage = 1
        this.getGraphicListFn()
        this.$refs.videoScrollView.refreshFinish() // 刷新完成
      }, 400);
    },
    viewAllTitleFn (data,index) {
      this.graphicList[index].showTitle = false
    },
  }
}
</script>

<style lang="scss" scoped>
@import './takeNotes.scss';
</style>